package com.mediacenter.activity;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.mediacenter.R;
import com.mediacenter.adapter.ContentShowAdapter;
import com.mediacenter.application.MApplication;
import com.mediacenter.site.model.Category;
import com.mediacenter.site.model.Genre;
import com.mediacenter.site.model.Show;
import com.mediacenter.site.model.Source;
import com.mediacenter.widget.ProgressManager;
import com.naduolai.android.ui.dialog.StandardAlertDialog;
import com.slidingmenu.lib.SlidingMenu;
import com.umeng.analytics.MobclickAgent;

/**
 * 数据查询Activity
 */
@SuppressLint("NewApi")
public class ListActivity extends BaseTopActivity {

	private Thread thread;

	Map<String, Bitmap> caches = new HashMap<String, Bitmap>();

	private GridView tableContentGridView;

	private ExecutorService dataExecutorService;

	private LayoutInflater inflater;

	private boolean recodeHeadRadioButton;

	private ListView leftNavigationListView;
	
	private Source modeSource;

	private ContentShowAdapter contentDataBaseAdapter;

	private RadioGroup headRadioGroup;
	
	private boolean appending;
	/**
	 * Application单例对象，存放Activity跳转相关参数
	 */
	protected MApplication application = MApplication.getInstance();
	
	private int leftItemClickPosition;
	
	private void showExceptionMessageDialog() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				showAlertDialog("警告", "非常抱歉,获取节目信息失败!", new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						finish();
					}
				});
			}
		});
	}
	
	/**
	 * 显示消息提示框,然后只给用户确定按钮
	 * @param title 
	 * @param message
	 */
	protected void showAlertDialog(String title,String message, OnCancelListener onCancelListener) {
		try {
			if(isFinishing()){
				return;
			}
			StandardAlertDialog.Builder ndAlertDialog = new StandardAlertDialog.Builder(ListActivity.this);
			ndAlertDialog.setTitle(title);
			ndAlertDialog.setMessage(message);
			ndAlertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			StandardAlertDialog dialog = ndAlertDialog.create();
			dialog.setOnCancelListener(onCancelListener);
			dialog.show();
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	@Override
	protected void onStop() {
		contentDataBaseAdapter.cleanCache();
		super.onStop();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(getClass().getName(), "onCreate");
		setContentView(R.layout.list_activity_main);
		inflater = ListActivity.this.getLayoutInflater();
		ImageView logo = (ImageView) findViewById(R.id.list_activity_logo);
		logo.setImageBitmap(application.getCurrentSource().getLogo());
		ProgressManager.getInstance().setActivity(this);
		ProgressManager.getInstance().showProcessDialog("loading...");
		thread = new Thread() {
			public void run() {
				try {
					application.getCurrentSource().init();
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							refreshView(headRadioGroup,true, true);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					showExceptionMessageDialog();
				} finally {
					runOnUiThread(new Runnable() {
						public void run() {
							ProgressManager.getInstance().cancel();
						}
					});
				}
			}
		};
//		thread.setPriority(Thread.MIN_PRIORITY);
		if (dataExecutorService != null) {
			dataExecutorService.shutdownNow();
		}
		dataExecutorService = Executors.newSingleThreadExecutor();
		dataExecutorService.submit(thread);
		tableContentGridView = (GridView) findViewById(R.id.table_content_gridView);
		contentDataBaseAdapter = new ContentShowAdapter(this, tableContentGridView);
		tableContentGridView.setAdapter(contentDataBaseAdapter);
		tableContentGridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Show show = modeSource.getShows().get(position);
				application.setCurrentShow(show);
				// 从这里入口
				Intent intent = new Intent(ListActivity.this, DetailsActivity.class);
				startActivity(intent);
			}
		});
		tableContentGridView.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				GridView gridView = (GridView) parent;
				int numcolumns = gridView.getNumColumns();
				int size = modeSource.getShows().size();
				int rows = (size % numcolumns == 0) ? (size / numcolumns) : (size / numcolumns + 1);
				int currentRow = ((position + 1) % numcolumns == 0) ? ((position + 1) / numcolumns)
						: ((position + 1) / numcolumns + 1);
				scaleAnim(ListActivity.this, parent, view);
				setSelectBackground(parent, view);
				if (currentRow != rows||appending) {
					android.util.Log.e(getClass().getName(), "position:" + position);
					android.util.Log.e(getClass().getName(), "hello");
					return;
				}
				appendShows();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
		
		tableContentGridView.setOnScrollListener(new OnScrollListener() {

			private int getLastVisiblePosition;
			private int lastVisiblePositionY;

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					// 滚动到底部
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						View v = (View) view.getChildAt(view.getChildCount() - 1);
						int[] location = new int[2];
						v.getLocationOnScreen(location);// 获取在整个屏幕内的绝对坐标
						int y = location[1];

						if (view.getLastVisiblePosition() != getLastVisiblePosition
								&& lastVisiblePositionY != y) {
							// 第一次拖至底部
							Toast.makeText(view.getContext(), "再次拖至底部，即可翻页", 500).show();
							getLastVisiblePosition = view.getLastVisiblePosition();
							lastVisiblePositionY = y;
							return;
						} else if (view.getLastVisiblePosition() == getLastVisiblePosition
								&& lastVisiblePositionY == y) {
							// 第二次拖至底部
							if (!appending) {
								appendShows();
							}
						}
					}

					// 未滚动到底部，第二次拖至底部都初始化
					getLastVisiblePosition = 0;
					lastVisiblePositionY = 0;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
					int totalItemCount) {

			}
		});
		tableContentGridView.setOnFocusChangeListener(onFocusChangeListener);
		leftNavigationListView = (ListView) findViewById(R.id.title_navigation_listView);
		leftNavigationListView.setAdapter(leftBaseAdapter);
		leftNavigationListView.setItemsCanFocus(true);
		leftNavigationListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				for (int i = 0; i < leftNavigationListView.getChildCount(); i++) {
					LinearLayout child = (LinearLayout) leftNavigationListView.getChildAt(i);
					child.setBackgroundResource(R.drawable.menu_selector);
				}
				view.setBackgroundResource(R.drawable.menu_focus);
				leftItemClickPosition = position;
				ProgressManager.getInstance().showProcessDialog("loading...");
				view.setBackgroundResource(R.drawable.menu_focus);
				thread = new Thread() {
					public void run() {
						try {
							Source source = application.getCurrentSource();
							Genre genre = source.getGenres().get(position);
							source.genreSelect(genre);
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									refreshView(null,false, false);
								}
							});
						} catch (Exception e) {
							e.printStackTrace();
							showExceptionMessageDialog();
						} finally {
							runOnUiThread(new Runnable() {
								public void run() {
									ProgressManager.getInstance().cancel();
								}
							});
						}
					}
				};
//				thread.setPriority(Thread.MIN_PRIORITY);
				dataExecutorService.shutdownNow();
				dataExecutorService = Executors.newSingleThreadExecutor();
				dataExecutorService.submit(thread);
			}
		});
		headRadioGroup = (RadioGroup) findViewById(R.id.head_title_radiogroup);
		// 各个站点有效的播放次数
		MobclickAgent.onEventBegin(ListActivity.this, "WEBSITE_PLAY_COUNT", application.getCurrentSource().getSourceThumb());
		
		
		SlidingMenu sm = getSlidingMenu();
		getSlidingMenu().setMode(SlidingMenu.RIGHT);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		sm.setSecondaryMenu(R.layout.listactivity);
		leftNavigationListView = (ListView) sm.getSecondaryMenu().findViewById(R.id.title_navigation_listView);
		leftNavigationListView.setAdapter(leftBaseAdapter);
//		getSupportFragmentManager()
//		.beginTransaction()
//		.replace(R.id.menu_frame_two, new SampleListFragment())
//		.commit();	
		sm.setFadeDegree(0.35f);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setSecondaryShadowDrawable(R.drawable.shadowright);
		sm.setShadowDrawable(R.drawable.shadow);
	}
	
	private void appendShows(){
		Toast.makeText(ListActivity.this, "加载下一页数据...", 500).show();
		thread = new Thread() {
			public void run() {
				try {
					appending = true;
					Source source = application.getCurrentSource();
					final boolean result = source.moreShows();
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							refreshView(tableContentGridView,false, false);
							if (result) {
								Toast.makeText(ListActivity.this, "下一页数据加载成功...", 500).show();
							}else {
								Toast.makeText(ListActivity.this, "下一页数据加载失败或已到达最后一页...", 500).show();
							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
					showExceptionMessageDialog();
				} finally {
					appending = false;
				}
			}
		};
//		thread.setPriority(Thread.MIN_PRIORITY);
		if (dataExecutorService == null || dataExecutorService.isShutdown()) {
			dataExecutorService = Executors.newSingleThreadExecutor();
		}
		dataExecutorService.submit(thread);
	}
	
	public static void setSelectBackground(AdapterView<?> parent, View view) {
		for (int i = 0; i < parent.getChildCount(); i++) {
			LinearLayout child = (LinearLayout) parent.getChildAt(i);
			ImageView imageView = (ImageView) child.findViewById(R.id.gridview_item_image);
			imageView.setBackgroundResource(R.drawable.background);
		}
		ImageView currentImageView = (ImageView) view.findViewById(R.id.gridview_item_image);
		currentImageView.setBackgroundResource(R.drawable.video_focus);
	}
	
	public static void scaleAnim(Context context, AdapterView<?> parent, View view) {
		for (int i = 0; i < parent.getChildCount(); i++) {
			View child = parent.getChildAt(i);
			if (child.getTag() == null || !(child.getTag() instanceof Animation)) {
				continue;
			}
			Animation animation = (Animation) child.getTag();
			ImageView imageView = (ImageView) child.findViewById(R.id.gridview_item_image);
			imageView.startAnimation(animation);
			child.setTag(null);
		}
		ImageView imageView1 = (ImageView) view.findViewById(R.id.gridview_item_image);
		imageView1.startAnimation(AnimationUtils.loadAnimation(context, R.anim.in_anim));
		view.setTag(AnimationUtils.loadAnimation(context, R.anim.out_anim));
	}

	private void refreshView(View focusView,boolean refreshHead, boolean refreshLeft) {
		try {
			modeSource = application.getCurrentSource().clone();
			contentDataBaseAdapter.setShows(modeSource.getShows());
			refreshHead(refreshHead);
			if (refreshLeft)
				leftBaseAdapter.notifyDataSetChanged();
			contentDataBaseAdapter.cleanCache();
			contentDataBaseAdapter.shutdownExecutorService();
			contentDataBaseAdapter.notifyDataSetChanged();
			MainActivity.resetSelect(tableContentGridView);
			if (focusView != null) {
				leftNavigationListView.setSelection(0);
				focusView.requestFocus();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {  
        @Override  
        public void onFocusChange(View v, boolean hasFocus) {  
            if (!hasFocus) {  
                MainActivity.resetSelect(v);
            }  
        }  
    };
	
	BaseAdapter leftBaseAdapter = new BaseAdapter() {
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.left_navigation_item, null);
			TextView textView = (TextView)layout.findViewById(R.id.left_navigation_item_button);
			TextView leftNavigationItemNum = (TextView) layout.findViewById(R.id.left_navigation_item_num);
			leftNavigationItemNum.setText((position + 1)+" ");
			Genre genre = modeSource.getGenres().get(position);
			textView.setText(genre.getTitle());
			layout.setLayoutParams(new ListView.LayoutParams(ListView.LayoutParams.MATCH_PARENT,56));
			if (leftItemClickPosition == position) {
				layout.setBackgroundResource(R.drawable.menu_focus);
			}else {
				layout.setBackgroundResource(R.drawable.menu_selector);
			}
			return layout;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public Object getItem(int position) {
			return modeSource== null || modeSource.getGenres() == null ? 0 : modeSource
					.getGenres().get(position);
		}

		@Override
		public int getCount() {
			return modeSource== null || modeSource.getGenres() == null ? 0 : modeSource
					.getGenres().size();
		}
	};

	private void refreshHead(boolean refreshHead) {
		if (!refreshHead || modeSource.getmCategories() == null)
			return;
		for (int i = 0; i < modeSource.getmCategories().size(); i++) {
			final int index = i;
			Category category = modeSource.getmCategories().get(index);
			final RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.homepage_tabgroup_item, null);
			radioButton.setLayoutParams(new LayoutParams(190, LayoutParams.MATCH_PARENT));
			radioButton.setId(i);
			radioButton.setText(category.getName());
			radioButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (!recodeHeadRadioButton) {
						recodeHeadRadioButton = true;
						return;
					}
					ProgressManager.getInstance().showProcessDialog("loading...");
					thread = new Thread() {
						public void run() {
							try {
								Source source = application.getCurrentSource();
								Category category = source.getmCategories().get(index);
								source.categorySelect(category);
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										refreshView(radioButton,false, true);
									}
								});
							} catch (Exception e) {
								e.printStackTrace();
								showExceptionMessageDialog();
							} finally {
								runOnUiThread(new Runnable() {
									public void run() {
										ProgressManager.getInstance().cancel();
									}
								});
							}
						}
					};
					thread.setPriority(Thread.MIN_PRIORITY);
					dataExecutorService.shutdownNow();
					dataExecutorService = Executors.newSingleThreadExecutor();
					dataExecutorService.submit(thread);
				}
			});
			headRadioGroup.addView(radioButton);
		}
		headRadioGroup.check(0);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		// 各个站点有效的播放次数
		MobclickAgent.onEventEnd(ListActivity.this, "WEBSITE_PLAY_COUNT", application.getCurrentSource().getSourceThumb());
	}


	
	@Override
	protected void onDestroy() {
		Log.e(getClass().getName(), "onDestroy");
		recodeHeadRadioButton = false;
		System.gc();
		if (thread != null) {
			thread.interrupt();
		}
		contentDataBaseAdapter.shutdownExecutorService();
		super.onDestroy();
	}

	/**
	 * 根据tag查找图片组件
	 * 
	 * @param viewGroup
	 * @param tag
	 * @return
	 */
	public static ImageView findImageViewByStringTag(ViewGroup viewGroup, String tag) {
		for (int i = 0; i < viewGroup.getChildCount(); i++) {
			View child = viewGroup.getChildAt(i);
			if (child instanceof ImageView) {
				ImageView imageView = (ImageView) child;
				Object tagObject = child.getTag();
				if (tagObject != null && tagObject instanceof String && tagObject.equals(tag)) {
					return imageView;
				}
			} else if (child instanceof ViewGroup) {
				ImageView imageView = findImageViewByStringTag((ViewGroup) child, tag);
				if (imageView != null) {
					return imageView;
				}
			}
		}
		return null;
	}
	
	@Override
	public void onLowMemory() {
		super.onLowMemory();
		if (contentDataBaseAdapter != null) {
			contentDataBaseAdapter.cleanCache();
		}
	}
}
